import * as Constant from '@/constant/index.js';
import * as regular from './regular.js';
import * as pageTo from './navTo.js';

// 返回上一页
export const routerBack = () => {
  let page = getCurrentPages();
  if (page && page.length > 1) {
    uni.navigateBack({
      delta: 1,
    });
  } else {
    history.back();
  }
};

export const navTo = (url) => {
  const re = regular.urlReg();

  if (re.test(url)) {
    // 外部网址
    console.log('外部网址');
    h5uni.navigateTo({
      url: `/pages/webview/index?url=${url}`,
    });
  } else {
    // 内部网址
    console.log('内部网址');
    // pageTo.navigateTo(url)
    const link = url + (url.includes('?') ? '&' : '?') + '_t=' + new Date().getTime();
    isUniapp ? pageTo.h5uniNavTo(link) : pageTo.navigateTo(link);
  }
};

export const setTimeoutFunc = (callback, time = 1000) => {
  const timer = setTimeout(() => {
    clearTimeout(time);
    callback();
  }, time);
};

// 编码
export const encode = (str) => {
  // 对字符串进行编码
  let encode = encodeURI(str);
  // 对编码的字符串转化base64
  let base64 = btoa(encode);
  return base64;
};

// 解码
export const decode = (str) => {
  let decode = decodeURI(str);
  let dec = atob(decode);
  return dec;
};

//生成10个1-100不重复的随机数
export const random = (number, length) => {
  // number生成的随机数个数， length生成的1到length之间的随机数
  var arr = [];
  while (arr.length < number) {
    //原数组长度为0，每次成功添加一个元素后长度加1，当数组添加最后一个数字之前长度为number即可
    var num = Math.floor(Math.random() * length); //生成一个0-300的随机整数
    if (arr.length === 0) {
      //如果数组长度为0则直接添加到arr数组
      arr.push(num);
    } else {
      for (var i = 0; i < arr.length; i++) {
        //当新生成的数字与数组中的元素不重合时则添加到arr数组
        if (arr.join(',').indexOf(num) < 0) {
          arr.push(num);
        }
      }
    }
  }
  return arr;
};

/**
 * 生成随机字符串 + 时间戳
 * @param {Number} len 字符长度
 */
export const randomString = (len) => {
  len = len || 32;
  let timestamp = new Date().getTime();
  /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  let maxPos = $chars.length;
  let randomStr = '';
  for (let i = 0; i < len; i++) {
    randomStr += $chars.charAt(Math.floor(Math.random() * maxPos));
  } // return randomStr + timestamp;
  return randomStr;
};

/**
 * 是否uniapp APP打开
 */
export const isUniapp = () => {
  var ua = navigator.userAgent.toLowerCase();
  var isUniapp = ua.indexOf('uni-app') != -1;
  if (isUniapp) {
    return true;
  } else {
    return false;
  }
};

/**
 * 获取当前路由地址（除开wxlsToken和time）
 * @param{Object} options 必传 页面路由传参
 */
export const currentPage = (options) => {
  let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
  let page = routes[routes.length - 1]; // 获取当前页面路由，也就是最后一个打开的页面路由
  let pages = page.route;
  Object.entries(options)
    .filter((item) => item[0] !== 'wxlsToken' && item[0] !== 'time')
    .map((item) => (pages += (pages.includes('?') ? '&' : '?') + item[0] + '=' + item[1]));
  return pages;
};

/**
 * 检测登录(url是否携带wxlsToken,没有则app没有登录)
 * @param{Object} options 必传 页面路由传参
 * @param{String} url 可选 登录回跳地址 默认：pages/index/index
 * @param{Boolean} isCurrentPage 可选 登录回跳地址 默认：false
 */
export const checkAppLogin = (param) => {
  let { options, url = 'pages/index/index', isCurrentPage = false } = param;
  let pages = isCurrentPage ? currentPage(options) : url;

  !options.wxlsToken &&
    uni.showModal({
      title: '未登录',
      content: '您未登录，需要登录后才能继续',
      cancelText: '以后再说',
      confirmText: '前往登录',
      success: (res) => {
        if (res.confirm) {
          let navToUrl = `${
            process.env.NODE_ENV === 'development' ? Constant.DEV_FRONTURL : Constant.PRO_FRONTURL
          }/#/${pages}${pages.includes('?') ? '&' : '?'}time=${new Date().getTime()}`;

          h5uni['redirectTo']({
            url: '/pages/user/back_login?url=' + navToUrl,
          });
        } else if (res.cancel) {
          h5uni.navigateBack();
        }
      },
    });

  return !!options.wxlsToken;
};

/**
 * 数字长度处理，加单位
 */
export const switchNum = (val) => {
  val = parseInt(val);
  if (val >= 10000) {
    return (val / 10000).toFixed(1) + 'W';
  } else {
    if (val < 1000) {
      return val;
    } else {
      return (val / 1000).toFixed(1) + 'K';
    }
  }
};

/**
 * 数组拆分成若干个为一组的新数组
 *  @param {Array} 数组
 *  @param {Number}  一组的个数
 */
export const chunkArray = (arr, num) => {
  let j = 0,
    o = j;
  let newArray = [];
  while (j < arr.length) {
    j += num;
    newArray.push(arr.slice(o, j));
    o = j;
  }
  return newArray;
};

/**
 * 数组按日期分组
 */
export const listGroupedByTime = (arr) => {
  let newArr = [];
  arr.forEach((item, i) => {
    let index = -1;
    let isExists = newArr.some((newItem, j) => {
      if (item.gainTimeStart == newItem.time) {
        index = j;
        return true;
      }
    });
    if (!isExists) {
      newArr.push({
        time: item.gainTimeStart,
        list: [item],
      });
    } else {
      newArr[index].list.push(item);
    }
  });
  return newArr;
};

/**
 * 找出数组里最接近当前时间的时间
 * @param{Array} arr 时间数组
 * @return 最接近当前的时间项
 */
export const findCloseToCurrentTime = (arr) => {
  const timestamp = Date.now();
  let min;
  let index = 0;
  arr.forEach(function (item, i) {
    const itemStamp = new Date(item).getTime();
    const interVal = Math.abs(timestamp - itemStamp);
    if (min == void 0) {
      min = interVal;
      return;
    }
    if (min > interVal) {
      min = interVal;
      index = i;
    }
  });
  return { item: arr[index], index: index };
};

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img、video标签里的style、width、height属性
 * 2.修改所有style里的width属性为max-width:100%
 * 3.img、video标签添加style属性：max-width:100%;height:auto
 * 4.去掉<br/>标签
 * @param html
 * @return string
 */
export const formatRichText = (html) => {
  // 去掉img标签里的style、width、height属性
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });

  // 去掉video标签里的style、width、height属性
  newContent = html.replace(/<video[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  // 修改所有style里的width属性为max-width:100%
  // 去掉所有style里的font-size属性
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match
      .replace(/width:[^;]+;/gi, 'max-width:100%;')
      .replace(/width:[^;]+;/gi, 'max-width:100%;');
    match = match.replace(/font-size:[^;]+;/gi, '');
    return match;
  });
  // 去掉<br/>标签
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  // img标签添加style属性：max-width:100%;height:auto
  newContent = newContent.replace(
    /\<img/gi,
    '<img style="max-width:100%;height:auto;display:block;margin:0px auto;"',
  );
  // video标签添加style属性：max-width:100%;height:auto
  newContent = newContent.replace(
    /\<video/gi,
    '<video style="max-width:100%;height:auto;display:block;margin:0px auto;"',
  );
  return newContent;
};

/**
 * 时间是否达到
 * @param {*} time 时间
 */
export const isTimeReached = (time) => {
  let start = new Date(time).getTime();
  let now = new Date().getTime();
  return now >= start;
};

/**
 * 获取路径后面带过来的参数——字符串分割分析法
 * @param {String} url
 */
export const getUrlParam = (url) => {
  let theParam = new Object();
  const index = url.indexOf('?');
  if (index != -1) {
    //确保‘？’不是最后一个字符串，即携带的参数不为空
    let str = url.substr(index + 1); //substr是字符串的用法之一，抽取指定字符的数目，这里抽取？后的所有字符
    const strs = str.split('&'); //将获取到的字符串从&分割，输出参数数组，即输出[参数1=xx,参数2=xx,参数3=xx,...]的数组形式
    for (let i = 0; i < strs.length; i++) {
      //遍历参数数组
      theParam[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]); //这里意思是抽取每个参数等号后面的值，unescape是解码的意思
    }
  }
  return theParam; //返回参数值
};

/**
 * 脱敏姓名
 */
export const desensitizedName = (str) => {
  if (!str) {
    console.log('姓名为空');
    return;
  }
  let str1 = str.substr(0, 1);
  let str2 = '';
  if (str.length >= 3) {
    let num1 = str.substr(1, str.length - 2).length;
    for (let i = 0; i < num1; i++) {
      str2 += ' *';
    }
    str2 += str.substr(-1);
  } else {
    str2 = ' *';
  }
  let str3 = str1 + str2;
  return str3;
};

/**
 * 脱敏手机号
 */
export const desensitizedPhone = (phone) => {
  const pho = /(\d{3})\d*(\d{4})/;
  return phone.replace(pho, '$1****$2');
};

// --------------数组转树结构-----------------
/**
 * 递归查找添加children
 * @param {数组数据} data
 * @param {存放返回结果} result
 * @param {父id} pid
 */
function getChildren(data, result, pid) {
  for (const item of data) {
    if (item.pid === pid) {
      const newItem = { children: [], ...item };
      result.push(newItem);
      getChildren(data, newItem.children, item.id);
    }
  }
}

/**
 * 转化方法
 * @param {数组数据} data
 * @param {父id} pid
 * @returns
 */
export function arrayToTree(data, pid) {
  let result = [];
  getChildren(data, result, pid);
  return result;
}
// --------------数组转树结构 END----------------

// ----------------树结构转数组--------------------
/**
 * 树结构数组扁平化
 * @param {*} data 树结构的数组
 * @param {*} childrenKey 子项key
 * @returns
 */
export function treeToArray(data, childrenKey = 'children') {
  return data.reduce((pre, cur) => {
    const { [childrenKey]: children = [], ...item } = cur;
    return pre.concat([{ ...item }], treeToArray(children));
  }, []);
}
// ----------------树结构转数组 END--------------------

/**
 * 根据数组元素某一个属性 将数组数据进行分类
 * @param {数组数据} arr
 * @param {fn传入将要分类的属性} fn
 * @description classifyArr(list,(item) => item.type)
 * @returns
 */
export function classifyArr(arr, fn) {
  const obj = {};
  arr.forEach((item) => {
    const key = JSON.stringify(fn(item));
    obj[key] = obj[key] || [];
    obj[key].push(item);
  });
  return Object.keys(obj).map((k) => {
    return obj[k];
  });
}

/**
 * 根据id查找所在目录路径
 * @param {树结构的数组数据} tree
 * @param {要查找的id} id
 * @param {初始路径} path
 * @param {查找的key值} key
 * @returns
 */
export function parseTreePath(tree, id, path = '', key = 'title') {
  for (let i = 0; i < tree.length; i++) {
    let tempPath = path;
    // 避免出现在最前面的/
    tempPath = `${tempPath ? tempPath + '/' : tempPath}${tree[i][key]}`;
    if (tree[i].id == id) return tempPath;
    else if (tree[i].children) {
      let reuslt = parseTreePath(tree[i].children, id, tempPath, key);
      if (reuslt) return reuslt;
    }
  }
}

/**
 * 根据id查找所在目录索引
 * @param {树结构的数组数据} tree
 * @param {要查找的id} id
 * @param {初始索引} index
 * @returns
 */
export function parseTreeIndex(tree, id, index = '') {
  for (let i = 0; i < tree.length; i++) {
    let tempPath = index;
    // 避免出现在最前面的/
    tempPath = `${tempPath ? tempPath + '/' : tempPath}${i}`;
    if (tree[i].id == id) return tempPath;
    else if (tree[i].children) {
      let reuslt = parseTreeIndex(tree[i].children, id, tempPath);
      if (reuslt) return reuslt;
    }
  }
}
